package filter;

import pojo.Worker;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/*"})
public class LoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 判断session
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        Worker worker = (Worker) request.getSession().getAttribute("worker");
        String spath = request.getServletPath();
        //
        //不需要过滤的url
        String[] urls = {"/login", "/json", ".js", ".css", ".ico", ".jpg", ".png"};
        boolean flag = true;
        for (String str : urls) {
            if (spath.contains(str)) {
                flag = false;
                break;
            }
        }
        if (flag) {
            if (worker != null) {
                chain.doFilter(request, response);
            } else {
                response.sendRedirect(request.getContextPath() + "/login?m=loginPage");
            }
        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
